package com.yinian.server.controller;


import cn.hutool.system.UserInfo;
import com.yinian.common.constant.JwtClaimsConstant;
import com.yinian.common.constant.MessageConstant;
import com.yinian.common.properties.JwtProperties;
import com.yinian.common.result.Result;
import com.yinian.common.utils.JwtUtil;
import com.yinian.common.utils.MailService;
import com.yinian.pojo.dto.UserLoginDTO;
import com.yinian.pojo.dto.UserRegisterDTO;
import com.yinian.pojo.dto.UserUpdateInformationDTO;
import com.yinian.pojo.dto.VerificationCodeDTO;
import com.yinian.pojo.entity.User;
import com.yinian.pojo.vo.UserLoginVO;
import com.yinian.pojo.vo.UserRegisterVO;
import com.yinian.server.mapper.UserMapper;
import com.yinian.server.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 *  登陆注册
 */
@RestController
@Slf4j
@Api(tags = "登陆注册相关接口")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private MailService mailService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 登录
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);

        User user = userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMAIL, user.getEmail());
        claims.put(JwtClaimsConstant.USER_NAME, user.getUserName());

        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUserName())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

/**
 * 获取验证码
 *
 * */
    @PostMapping("/get-verificationCode")
    public Result sendTextMail(@RequestBody VerificationCodeDTO verificationCodeDTO){
        log.info("获取验证码：{}", verificationCodeDTO);
        userService.sendVerificationCode(verificationCodeDTO);
        return Result.success();
    }

    /**
     * 注册
     *
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("/code-login")
    @ApiOperation(value = "用户注册")
    public Result<UserRegisterVO> login(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册：{}", userRegisterDTO);
        String email = userRegisterDTO.getEmail();
        String code = userRegisterDTO.getCode();
        String codeServer = (String) redisTemplate.opsForValue().get(email + "_code");
        System.out.println(codeServer);
        System.out.println(code);


        if (codeServer == null) {
            return Result.error(MessageConstant.ACCOUNT_OR_CODE_ERROR);
        }
        if (codeServer.equals(code) == false) {
            return Result.error(MessageConstant.VERIFICATION_CODE_ERROR);
        }

        User user = userService.register(userRegisterDTO);
        if (user == null) {
            String initName = "长乐" + UUID.randomUUID().toString().substring(0, 6);
            String initPassword = UUID.randomUUID().toString().substring(0, 11);
            mailService.sendTextMailMessage(
                    email,
                    "账号初始密码：",
                    "请谨慎保存您的账号密码：" + initPassword
            );
            user = new User();
            user.setUserName(initName);
            user.setEmail(email);
            user.setPassword(DigestUtils.md5DigestAsHex(initPassword.getBytes()));

            userService.save(user);
        }
        UserRegisterVO userRegisterVO = new UserRegisterVO();
        BeanUtils.copyProperties(user, userRegisterVO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMAIL, userRegisterVO.getEmail());
        claims.put(JwtClaimsConstant.USER_NAME, userRegisterVO.getUserName());

        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        userRegisterVO.setToken(token);
        redisTemplate.delete(email + "_code");
        return Result.success(userRegisterVO);
    }


    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/update-user-information")
    @ApiOperation("修改用户信息")
    public Result updateUserInformation(@RequestBody UserUpdateInformationDTO userUpdateInformationDTO) {
        userService.updateUserInformation(userUpdateInformationDTO);
        return Result.success();
    }

}
